<template>
    <el-card>
        <el-form :model="addForm" status-icon :rules="rules" ref="addForm" label-width="100px">
            <el-form-item label="用户名" prop="username">
                <el-input autocomplete="off" v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input autocomplete="off" v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input autocomplete="off" v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input autocomplete="off" v-model="addForm.mobile"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('addForm')">立即创建</el-button>
                <el-button @click="resetForm('addForm')">取消</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>
<script>
export default {
    data() {
        return {
            addForm: {
                username: "",
                password: "",
                email: "",
                mobile: "",
            },
            rules: {
                username: [
                    { required: true, trigger: 'blur', message: '请输入内容' },
                    { max: 5, min: 3, message: '3-5个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, trigger: 'blur', message: '请输入内容' },
                    { max: 12, min: 6, message: '6-12个字符', trigger: 'blur' }
                ]
            },

        }
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate(
                async (valid) => {
                    if (valid) {
                        const { data: { data, meta } } = await this.$http.post('users', this.addForm);
                        if (meta.msg == '用户名已存在') return this.$message.warning('用户名已存在,请重新输入');
                        this.$message.success('添加成功');
                        this.$router.replace('/userlist');
                    }
                });
        },
        resetForm(formName) {
            this.$router.replace('/userlist');
            this.$refs[formName].resetFields();
        }
    }
}
</script>